package com.pvdnc.worldmagisk;

import android.content.Context;
import android.telecom.Call;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Shell {
    private static final ALog LOG=new ALog(Shell.class);

    private Context mContext;

    public Shell(Context context, String startupCommand) throws IOException{
        mContext=context;
    }

    private int mPort;

    public Shell(int port) throws IOException {
        mPort=port;
        init();
    }

    private ShellStream mStream;

    private void init() throws IOException {
        Callable<ShellStream> callable=new Callable<ShellStream>() {
            @Override
            public ShellStream call() throws IOException {
                Socket socket=new Socket(InetAddress.getLocalHost(),mPort);
                OutputStream os= socket.getOutputStream();
                InputStream is=socket.getInputStream();
                mStream=new ShellStream(is,os);
                LOG.d("shell stream has been prepared");
                return mStream;
            }
        };
        FutureTask<ShellStream> futureTask=new FutureTask<>(callable);
        new Thread(futureTask,"ConnectToSocket").start();
        try {
            futureTask.get();
        } catch (ExecutionException | InterruptedException e) {
            throw new IOException("fail to connect to socket",e);
        }
    }

    public String execute(String cmd,boolean wait) throws IOException {
        if(!wait) {
            mStream.stdout.write(cmd.getBytes());
            mStream.stdout.flush();
            return "";
        }
        return new String(mStream.execute(cmd));
    }
}
